<?php

namespace App\Http\Controllers\Admin\Administration;

use App\Http\Controllers\Controller;
use App\Models\administration\MsgModel;
use Illuminate\Http\Request;

class Msg extends Controller
{

    /**
     * Notes:列表
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $type = $request->input('type', '');
        $status = $request->input('status', '');
        $staff_id = $request->input('staff_id', '');
        $create_start = $request->input('create_start', '');
        $create_end = $request->input('create_end', '');

        $query = MsgModel::query()->with('staff');

        if($type){
            $query = $query->where('type', $type);
        }

        if($status != ''){
            $query = $query->where('status', $status);
        }

        if($staff_id){
            $query = $query->where('staff_id', $staff_id);
        }

        if($create_start && $create_end){
            $query = $query->whereBetween('created_at', [$create_start, $create_end]);
        }

        $total = $query->count('id');
        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {
            $res = [
                'id' => $item->id,
                'type' => $item->type,
                'type_text' => MsgModel::TYPE[$item->type],
                'staff_name' => $item->staff ? $item->staff->name : '',
                'content' => $item->content,
                'status' => $item->status,
                'status_text' => MsgModel::STATUS[$item->status],
                'created_at' => $item->created_at->toDateTimeString(),
            ];
            return $res;
        });

        return $this->success(['list' => $list, 'total' => $total]);
    }


    /**
     * Notes:标记已读
     * User: xiangzi
     * Date: 2024/9/21
     * Time: 11:03
     * @return \Illuminate\Http\JsonResponse
     */
    public function read(Request $request, $id){
        $model = MsgModel::find($id);
        if (!$model) {
            return $this->error('数据不存在');
        }

        $model->status = 1;
        $model->save();

        return $this->success();
    }

    /**
     * Notes:取消已读
     * User: xiangzi
     * Date: 2024/9/21
     * Time: 11:03
     * @return \Illuminate\Http\JsonResponse
     */
    public function cancel(Request $request, $id){
        $model = MsgModel::find($id);
        if (!$model) {
            return $this->error('数据不存在');
        }

        $model->status = 0;
        $model->save();

        return $this->success();
    }



}
